package me.fanwu.services.alipay.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayMarketingCdpAdvertiseCreateRequest;
import com.alipay.api.response.AlipayMarketingCdpAdvertiseCreateResponse;
import com.google.common.collect.ImmutableMap;
import me.fanwu.services.alipay.AdvertisementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/*
 * Wupher 编写于 2016/11/3.
 */
@Service
public class AdvServiceImpl implements AdvertisementService {

    private static final Logger log = LoggerFactory.getLogger(AdvServiceImpl.class);
    private AlipayClient alipayClient;

    @Autowired
    public AdvServiceImpl(AlipayClient alipayClient) {
        this.alipayClient = alipayClient;
    }

    @Override
    public String createAdv(String url, String height, String token) {
        JSONObject bizeContents = new JSONObject(8);
        Map<String,String >adv_rule = ImmutableMap.of("shop_id","2016103100077000000000013454");
        bizeContents.put("ad_code", "CDP_OPEN_MERCHANT");
        bizeContents.put("content_type", "URL");
        bizeContents.put("content", url);
        bizeContents.put("action_url",url);
        bizeContents.put("ad_rules", adv_rule);
        bizeContents.put("height", height);
        AlipayMarketingCdpAdvertiseCreateRequest request = new AlipayMarketingCdpAdvertiseCreateRequest();
        AlipayMarketingCdpAdvertiseCreateResponse response;
        request.setBizContent(bizeContents.toJSONString());
        try {
            response = alipayClient.execute(request,token);
        } catch (AlipayApiException e) {
            log.error("调用错误", e);
            e.printStackTrace();
            return null;
        }

        if (!response.isSuccess()){
            log.error("response -- " + response.getSubMsg());
            log.error(response.toString());
        }

        return response.getAdId();
    }



}
